<?php

// 雪里开简易预约制访客管理系统 V1.0（2025.05.20）
// 演示地址: http://fangke.chalide.cn
// 更新关注: /weivote/yuyuefangke
// 文件路径: sys/listu.php
// 文件大小: 20329 字节
// 最后修改时间: 2025-05-20 22:23:10
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 学生列表管理
 * 功能反馈:15058593138@qq.com
 */

// 获取分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$pageSize = 10;

// 获取搜索参数
$search_field = get_param('search_field', 'xh');
$search_value = get_param('search_value', '');

// 处理AJAX请求
if (isset($_GET['act'])) {
    $db = new MySQLDB();
    
    switch ($_GET['act']) {
        case 'add':
            // 获取表单参数
            $xh = post_param('xh');
            $pwd = post_param('pwd', $xh); // 默认密码与学号相同
            $name = post_param('name');
            $tel = post_param('tel');
            $type = post_param('type', 'stu');
            $status = post_param('status', '1');
            $memo = post_param('memo');
            
            // 简单验证
            if (!$xh || !$name) {
                json_error('学号和姓名不能为空');
            }
            
            // 检查学号是否已存在
            $exists = $db->getOne("SELECT * FROM `stux` WHERE `xh` = '" . $db->escape($xh) . "'");
            if ($exists) {
                json_error('学号已存在，请检查后重试');
            }
            
            // 新增数据
            $data = [
                'xh' => $xh,
                'pwd' => $pwd,
                'name' => $name,
                'tel' => $tel,
                'type' => $type,
                'status' => $status,
                'memo' => $memo
            ];
            
            $result = $db->insert('stux', $data);
            
            if ($result) {
                json_success('添加成功');
            } else {
                json_error('添加失败：' . $db->getError());
            }
            break;
            
        case 'edit':
            // 获取表单参数
            $id = post_param('id');
            $name = post_param('name');
            $tel = post_param('tel');
            $type = post_param('type');
            $status = post_param('status');
            $memo = post_param('memo');
            
            // 简单验证
            if (!$id || !$name) {
                json_error('ID和姓名不能为空');
            }
            
            // 更新数据
            $data = [
                'name' => $name,
                'tel' => $tel,
                'type' => $type,
                'status' => $status,
                'memo' => $memo
            ];
            
            // 如果密码不为空，则更新密码
            $pwd = post_param('pwd');
            if ($pwd) {
                $data['pwd'] = $pwd;
            }
            
            $result = $db->update('stux', $data, "id = '$id'");
            
            if ($result) {
                json_success('更新成功');
            } else {
                json_error('更新失败：' . $db->getError());
            }
            break;
            
        case 'delete':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 删除数据
            $result = $db->delete('stux', "id = '$id'");
            
            if ($result) {
                json_success('删除成功');
            } else {
                json_error('删除失败：' . $db->getError());
            }
            break;
            
        case 'batch_delete':
            // 获取参数
            $ids = post_param('ids');
            
            // 简单验证
            if (!$ids) {
                json_error('ID不能为空');
            }
            
            // 处理ID参数
            $id_arr = explode(',', $ids);
            $id_arr = array_map('intval', $id_arr);
            $id_str = implode(',', $id_arr);
            
            // 删除数据
            $result = $db->delete('stux', "id IN ($id_str)");
            
            if ($result) {
                json_success('批量删除成功');
            } else {
                json_error('批量删除失败：' . $db->getError());
            }
            break;
            
        case 'status':
            // 获取参数
            $id = post_param('id');
            $status = post_param('status');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 更新状态
            $result = $db->update('stux', ['status' => $status], "id = '$id'");
            
            if ($result) {
                json_success('状态更新成功');
            } else {
                json_error('状态更新失败：' . $db->getError());
            }
            break;
            
        case 'detail':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 查询详情
            $row = $db->getOne("SELECT * FROM `stux` WHERE `id` = '$id'");
            
            if ($row) {
                // 屏蔽密码
                $row['pwd'] = '';
                json_success('获取成功', $row);
            } else {
                json_error('获取失败：记录不存在');
            }
            break;
    }
    exit;
}

// 构建查询条件
$where = '1=1';
if ($search_value) {
    $db = new MySQLDB();
    $search_value = $db->escape($search_value);
    $where .= " AND `$search_field` LIKE '%$search_value%'";
}

// 获取分页数据
$db = new MySQLDB();
$result = $db->getPageList('stux', $where, 'id DESC', $page, $pageSize);

$list = $result['list'];
$total = $result['total'];
$totalPage = $result['totalPage'];

// 加载页头
require_once './inc/head.php';
?>

<div class="container">
    <div class="search-bar">
        <div class="row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div class="col-left">
                <h2 style="margin: 0;">学生列表</h2>
            </div>
            <div class="col-right">
                <button type="button" class="btn btn-primary" onclick="showAddForm()">添加学生</button>
            </div>
        </div>
        
        <form action="" method="get" class="search-form" style="display: flex; margin-bottom: 15px;">
            <input type="hidden" name="do" value="listu">
            <select name="search_field" class="search-select">
                <option value="xh" <?php echo $search_field == 'xh' ? 'selected' : ''; ?>>学号</option>
                <option value="name" <?php echo $search_field == 'name' ? 'selected' : ''; ?>>姓名</option>
                <option value="tel" <?php echo $search_field == 'tel' ? 'selected' : ''; ?>>电话</option>
            </select>
            <input type="text" name="search_value" class="search-input" placeholder="请输入搜索内容" value="<?php echo htmlspecialchars($search_value); ?>">
            <button type="submit" class="search-btn">查询</button>
        </form>
    </div>
    
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th width="20"><input type="checkbox" onclick="selectAll(this, 'input[name=ids]')"></th>
                    <th>ID</th>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>电话</th>
                    <th>类型</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($list)): ?>
                <?php foreach ($list as $item): ?>
                <tr>
                    <td><input type="checkbox" name="ids" value="<?php echo $item['id']; ?>"></td>
                    <td><?php echo $item['id']; ?></td>
                    <td><?php echo htmlspecialchars($item['xh']); ?></td>
                    <td><?php echo htmlspecialchars($item['name']); ?></td>
                    <td><?php echo htmlspecialchars($item['tel']); ?></td>
                    <td>
                        <?php 
                        switch ($item['type']) {
                            case 'stu': echo '学生'; break;
                            case 'sus': echo '门卡'; break;
                            case 'sys': echo '系统'; break;
                            default: echo $item['type']; break;
                        }
                        ?>
                    </td>
                    <td><?php echo $item['status'] == 1 ? '<span style="color: green;">启用</span>' : '<span style="color: red;">禁用</span>'; ?></td>
                    <td>
                        <button type="button" class="btn btn-default btn-sm" onclick="showDetail(<?php echo $item['id']; ?>)">详</button>
                        <button type="button" class="btn btn-primary btn-sm" onclick="showEditForm(<?php echo $item['id']; ?>)">编</button>
                        <?php if ($item['status'] == 1): ?>
                        <button type="button" class="btn btn-danger btn-sm" onclick="changeStatus(<?php echo $item['id']; ?>, 0, function() { window.location.reload(); })">禁</button>
                        <?php else: ?>
                        <button type="button" class="btn btn-success btn-sm" onclick="changeStatus(<?php echo $item['id']; ?>, 1, function() { window.location.reload(); })">启</button>
                        <?php endif; ?>
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteRecord(<?php echo $item['id']; ?>, function() { window.location.reload(); })">删</button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="8" align="center">暂无数据</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > 0): ?>
    <div class="table-footer">
        <div class="table-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo $totalPage; ?> 页</div>
        <div class="table-actions">
            <button type="button" class="btn btn-danger" onclick="batchDelete('ids')">批量删除</button>
        </div>
        <?php echo paginate($page, $totalPage, '?do=listu&search_field=' . urlencode($search_field) . '&search_value=' . urlencode($search_value)); ?>
    </div>
    <?php endif; ?>
</div>

<script>
// 显示添加表单
function showAddForm() {
    let content = `
    <form id="add-form">
        <div class="form-group">
            <label class="form-label">学号</label>
            <input type="text" name="xh" class="form-control" required data-name="学号">
        </div>
        <div class="form-group">
            <label class="form-label">密码</label>
            <input type="password" name="pwd" class="form-control" placeholder="默认与学号相同">
        </div>
        <div class="form-group">
            <label class="form-label">姓名</label>
            <input type="text" name="name" class="form-control" required data-name="姓名">
        </div>
        <div class="form-group">
            <label class="form-label">电话</label>
            <input type="text" name="tel" class="form-control">
        </div>
        <div class="form-group">
            <label class="form-label">类型</label>
            <select name="type" class="form-select">
                <option value="stu">学生</option>
                <option value="sus">门卡</option>
                <option value="sys">系统</option>
            </select>
        </div>
        <div class="form-group">
            <label class="form-label">状态</label>
            <div>
                <label class="form-checkbox">
                    <input type="radio" name="status" value="1" checked>
                    <span>启用</span>
                </label>
                <label class="form-checkbox">
                    <input type="radio" name="status" value="0">
                    <span>禁用</span>
                </label>
            </div>
        </div>
        <div class="form-group">
            <label class="form-label">备注</label>
            <textarea name="memo" class="form-control" rows="3"></textarea>
        </div>
    </form>
    `;
    
    showMask(content, '添加学生', [
        {
            text: '取消',
            class: 'mask-button-default',
            click: closeMask
        },
        {
            text: '确定添加',
            class: 'mask-button-primary',
            click: function() {
                if (!validateForm('add-form')) return;
                
                ajaxRequest('?do=listu&act=add', getFormData('add-form'), function(res) {
                    if (res.code === 0) {
                        showToast(res.msg, 'success');
                        closeMask();
                        window.location.reload();
                    } else {
                        showToast(res.msg, 'error');
                    }
                });
            }
        }
    ]);
}

// 显示编辑表单
function showEditForm(id) {
    ajaxRequest('?do=listu&act=detail', {id: id}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            let content = `
            <form id="edit-form">
                <input type="hidden" name="id" value="${data.id}">
                <div class="form-group">
                    <label class="form-label">学号</label>
                    <input type="text" class="form-control" value="${data.xh}" readonly>
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" name="pwd" class="form-control" placeholder="不修改请留空">
                </div>
                <div class="form-group">
                    <label class="form-label">姓名</label>
                    <input type="text" name="name" class="form-control" value="${data.name}" required data-name="姓名">
                </div>
                <div class="form-group">
                    <label class="form-label">电话</label>
                    <input type="text" name="tel" class="form-control" value="${data.tel || ''}">
                </div>
                <div class="form-group">
                    <label class="form-label">类型</label>
                    <select name="type" class="form-select">
                        <option value="stu" ${data.type === 'stu' ? 'selected' : ''}>学生</option>
                        <option value="sus" ${data.type === 'sus' ? 'selected' : ''}>门卡</option>
                        <option value="sys" ${data.type === 'sys' ? 'selected' : ''}>系统</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">状态</label>
                    <div>
                        <label class="form-checkbox">
                            <input type="radio" name="status" value="1" ${data.status === '1' ? 'checked' : ''}>
                            <span>启用</span>
                        </label>
                        <label class="form-checkbox">
                            <input type="radio" name="status" value="0" ${data.status === '0' ? 'checked' : ''}>
                            <span>禁用</span>
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">备注</label>
                    <textarea name="memo" class="form-control" rows="3">${data.memo || ''}</textarea>
                </div>
            </form>
            `;
            
            showMask(content, '编辑学生', [
                {
                    text: '取消',
                    class: 'mask-button-default',
                    click: closeMask
                },
                {
                    text: '确定修改',
                    class: 'mask-button-primary',
                    click: function() {
                        if (!validateForm('edit-form')) return;
                        
                        ajaxRequest('?do=listu&act=edit', getFormData('edit-form'), function(res) {
                            if (res.code === 0) {
                                showToast(res.msg, 'success');
                                closeMask();
                                window.location.reload();
                            } else {
                                showToast(res.msg, 'error');
                            }
                        });
                    }
                }
            ]);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 显示详情
function showDetail(id) {
    ajaxRequest('?do=listu&act=detail', {id: id}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            // 转换类型显示
            let typeText = '';
            switch (data.type) {
                case 'stu': typeText = '学生'; break;
                case 'sus': typeText = '门卡'; break;
                case 'sys': typeText = '系统'; break;
                default: typeText = data.type; break;
            }
            
            // 转换状态显示
            let statusText = data.status == 1 ? '<span style="color: green;">启用</span>' : '<span style="color: red;">禁用</span>';
            
            let content = `
            <div class="detail-item">
                <div class="detail-label">ID:</div>
                <div class="detail-value">${data.id}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">学号:</div>
                <div class="detail-value">${data.xh}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">姓名:</div>
                <div class="detail-value">${data.name}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">电话:</div>
                <div class="detail-value">${data.tel || '未设置'}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">类型:</div>
                <div class="detail-value">${typeText}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">状态:</div>
                <div class="detail-value">${statusText}</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">备注:</div>
                <div class="detail-value">${data.memo || '无'}</div>
            </div>
            `;
            
            showMask(content, '学生详情', [
                {
                    text: '关闭',
                    class: 'mask-button-default',
                    click: closeMask
                },
                {
                    text: '编辑',
                    class: 'mask-button-primary',
                    click: function() {
                        closeMask();
                        showEditForm(id);
                    }
                }
            ]);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 选择全部
function selectAll(checkbox, selector) {
    const items = document.querySelectorAll(selector);
    items.forEach(function(item) {
        item.checked = checkbox.checked;
    });
}
</script>

<style>
.detail-item {
    display: flex;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}
.detail-label {
    width: 80px;
    font-weight: bold;
}
.detail-value {
    flex: 1;
}
.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px 0;
}
.table-info {
    margin-bottom: 10px;
}
.table-actions {
    margin-bottom: 10px;
}
</style>
